package com.yifi.system.controller;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.aop.Inject;
import com.jfinal.core.JFinal;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.yifi.common.IOHelper;
import com.yifi.common.UserAgentUtil;
import com.yifi.common.base.BaseController;
import com.yifi.common.model.AjaxResult;
import com.yifi.common.utils.DateUtils;
import com.yifi.common.utils.JfinalUtil;
import com.yifi.common.utils.ToolSession;
import com.yifi.common.utils.ToolString;
import com.yifi.system.service.MisAttachService;
import com.yifi.system.service.UploadFileService;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cz.mallat.uasparser.UserAgentInfo;

/** 
* @ClassName: SysFileController 
* @Description: TODO
* @author 姚善利
* @date 2021-11-2 8:37:04 
*  
*/

@Path(value="/sysfile",viewPath = "/")
public class SysFileController extends BaseController {

	public void index()
	{
		//关联主ID
		String m_id=getPara("m_id","all");
		set("m_id", m_id);
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		set("cdoc_type", cdoc_type);
		//是否是多文件上传
		String ctype=getPara("ctype","multi");
		set("ctype", ctype);
		//是否可编辑
		String dotype=getPara("dotype","edit");
		set("dotype", dotype);
		render("system/sysfilelist.html");
	}
	//文件列表
	public void list()
	{
		//文件名
		String cfiletitle=getPara("cfiletitle","");
		//关联主ID
		String m_id=getPara("m_id","all");
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		List<String> paraList=new ArrayList<String>();
		String sqlSelect="select *  ";
		String sqlExcept=" from mis_attach where 1=1 ";
		if(StrUtil.isNotEmpty(cfiletitle))
		{
			//sqlExcept+=" and cfiletitle like '%"+cfiletitle+"%' ";
			sqlExcept+=" and cfiletitle like ? ";
			paraList.add("%"+cfiletitle+"%");
		}
		if(!m_id.equals("all"))
		{
			//sqlExcept+=" and m_id ='"+m_id+"' ";
			sqlExcept+=" and m_id =? ";
			paraList.add(m_id);
		}
		if(!cdoc_type.equals("all"))
		{
			//sqlExcept+=" and cdoc_type = '"+cdoc_type+"' ";
			sqlExcept+=" and cdoc_type =? ";
			paraList.add(cdoc_type);
		}
		renderJson(getDataTable(sqlSelect, sqlExcept,paraList.toArray()));
		
	}
	
	@Inject
	private UploadFileService uploadFileService;
	@Inject
	private MisAttachService misAttachService; 
	
	//新增单文件
	public void addSingle()
	{
		//关联主ID
		String m_id=getPara("m_id","all");
		set("m_id", m_id);
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		set("cdoc_type", cdoc_type);
		render("system/sysfilesingle.html");
	}
	
	
	public void uploadSingle()
	{
		UploadFile uploadFile=getFile();
		//关联主ID
		String m_id=getPara("m_id","all");
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		
		Record recordF = uploadFileService.uploadFile(getResponse(), getRequest(), uploadFile, "");

		String filename = recordF.getStr("fname");
		String filetype = recordF.getStr("fext");
		String fileurl = recordF.getStr("furl");
		String filesize = recordF.getStr("fsize");
		String filedate = recordF.getStr("fdate");
		
		String userAgent = getRequest().getHeader("User-Agent");
		UserAgentInfo userAgentInfo = null;
		try {
			userAgentInfo = UserAgentUtil.uasParser.parse(userAgent);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String osname = userAgentInfo.getOsName();
		
		if(misAttachService.add(IdUtil.fastUUID(), filename, filedate, filetype, m_id,
				ToolSession.getUser(this).getCname(), ToolSession.getUser(this).getCdept(),
				"", "", "1", filesize, cdoc_type, "",fileurl,osname))
		{
	        AjaxResult ajax = AjaxResult.success();
	        ajax.put("fileName", "");
	        ajax.put("url", "");
			renderJson(ajax);
		}
		else
		{
	        AjaxResult ajax = AjaxResult.error("文件上传失败");
			renderJson(ajax);
		}
	}
	
	//新增多文件
	public void addMulti()
	{
		//关联主ID
		String m_id=getPara("m_id","all");
		set("m_id", m_id);
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		set("cdoc_type", cdoc_type);
		render("system/sysfilemulti.html");
	}
	
	public void uploadMulti()
	{
		List<UploadFile> listUploadFiles=getFiles();

		//关联主ID
		String m_id=getPara("m_id","all");
		//文件类别
		String cdoc_type=getPara("cdoc_type","all");
		
		List<Record> listRecs = uploadFileService.uploadFile(getResponse(), getRequest(), listUploadFiles);
		
		for (Record recordF : listRecs) {
			String filename = recordF.getStr("fname");
			String filetype = recordF.getStr("fext");
			String fileurl = recordF.getStr("furl");
			String filesize = recordF.getStr("fsize");
			String filedate = recordF.getStr("fdate");
			
			String userAgent = getRequest().getHeader("User-Agent");
			UserAgentInfo userAgentInfo = null;
			try {
				userAgentInfo = UserAgentUtil.uasParser.parse(userAgent);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String osname = userAgentInfo.getOsName();
			
			misAttachService.add(IdUtil.fastUUID(), filename, filedate, filetype, m_id,
					ToolSession.getUser(this).getCname(), ToolSession.getUser(this).getCdept(),
					"", "", "1", filesize, cdoc_type, "",fileurl,osname);
		}
		
		AjaxResult ajax = AjaxResult.success();
        ajax.put("fileNames", "");
        ajax.put("urls", "");
		renderJson(ajax);
	}
	//删除文件
	public void remove()
	{
		String ids=getPara("ids","");
		ids=ToolString.getIdsToStr(ids);

		String uploadPath = IOHelper.GetUploadPath();
		String sql="select * from mis_attach where id in ("+ids+")";
		List<Record> list=Db.find(sql);
		for (Record record : list) {
			String furl=record.getStr("cfull_url");
			String filePath = uploadPath + furl;
			File delFile = new File(filePath);
			delFile.delete();
		}
		sql="delete from mis_attach where id in ("+ids+")";
		if(Db.update(sql)>0)
		{
			renderJson(success("删除成功！"));
		}
		else
		{
			renderJson(error("删除失败！"));
		}
	}
	
	// 单文件下载
	protected static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

	public void downfiles() {
		String uploadPath = IOHelper.GetUploadPath();

		String ids = getPara("ids", "");
		ids=ToolString.getIdsToStr(ids);
		String sql = "select * from mis_attach where id in ("+ids+") ";
		List<Record> list = Db.find(sql);
		if(list.size()==1)
		{
			Record record =list.get(0);
			String cfiletitle = record.getStr("cfiletitle");
			String cfull_url = record.getStr("cfull_url");
			HttpServletResponse response = getResponse();
			try {
				ServletContext servletContext = JFinal.me().getServletContext();
				// ---------
				response.setHeader("Accept-Ranges", "bytes");
				response.setHeader("content-disposition",
						"attachment;" + JfinalUtil.encodeFileName(getRequest(), cfiletitle)); //
				String contentType = servletContext.getMimeType(cfiletitle);
				response.setContentType(contentType != null ? contentType : DEFAULT_CONTENT_TYPE);

				OutputStream out = response.getOutputStream();

				String fullpath=uploadPath+cfull_url;
				// 创建输入流读取文件
				InputStream is = new FileInputStream(fullpath);
				if (is != null) {
					byte[] b = new byte[1024];
					int length;
					while ((length = is.read(b)) > 0) {
						out.write(b, 0, length);
					}
					// 关闭和释放流
					is.close();
				}
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} // 创建页面返回方式为输出流，可弹出下载框

			renderNull();
		} 
		else if(list.size()>1)
		{
			List<Map<String, Object>> listF = new ArrayList<Map<String, Object>>();
			for (Record record : list) {
				
				if (record != null) {
					String cfiletitle = record.getStr("cfiletitle");
					String cfull_url = record.getStr("cfull_url");

					Map<String, Object> map = new HashMap<String, Object>();
					map.put("file", cfiletitle);
					
					String fullpath=uploadPath+cfull_url;
					// 创建输入流读取文件
					InputStream is=null;
					try {
						is = new FileInputStream(fullpath);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					map.put("is", is);
					listF.add(map);
				}
			}

			String text = DateUtils.parseDateToStr("yyyyMMddHHmmssSSS", DateUtils.getNowDate());
			getResponse().setHeader("Accept-Ranges", "bytes");
			getResponse().setHeader("content-type", "application/octet-stream");
			getResponse().setContentType("multipart/form-data");//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型   
			getResponse().setHeader("Content-Disposition", "attachment;fileName="+text + ".zip");
			try {
				ZipOutputStream zipstream=new ZipOutputStream(getResponse().getOutputStream());
	            DataInputStream dis=null;
				for (Map<String,Object> file:listF) {
					InputStream instream =(InputStream)file.get("is");
					String fileName =file.get("file").toString();
					if (instream==null) {
						continue;
					}
	                dis=new DataInputStream(new BufferedInputStream(instream));
					ZipEntry entry = new ZipEntry(fileName);
					zipstream.putNextEntry(entry);
					
					byte[] b = new byte[1024];
					int length;
					while((length=instream.read(b))>0){
						zipstream.write(b,0,length);  
					}
					
					instream.close();
					if(dis!=null){
	                    dis.close();
	                }
					zipstream.closeEntry();
					zipstream.flush();
				}
				zipstream.finish();
				zipstream.close();
			} catch (IOException e) {   
				new RuntimeException(e.getMessage());   
			}  

			renderNull();
		}
		else if(list.size()<=0) {
			renderJson(error("文件不存在！"));
		}
	}

}
